//
//  WBNewFeatureView.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/8/1.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    @IBAction func enterStatus() {
        removeFromSuperview()
    }
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var scrollView: UIScrollView!
    class func newFeatureView() -> WBNewFeatureView{
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        
        //从xib加载的视图默认是600*600
        v.frame = UIScreen.main.bounds
        return v
    }
    
    override func awakeFromNib() {
        print(bounds);   //如果使用自动布局设计界面，从xib加载默认是600*600
        let count = 4;
        
        let rect = UIScreen.main.bounds
        for i in 0..<count{
            let imageName = "new_feature_\(i+1)"
            let iv = UIImageView(image:UIImage(named: imageName))
            
            //设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(iv)
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(count+1)*rect.width, height: rect.height)
        
        scrollView.bounces = false   //关闭弹簧效果
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        //隐藏按钮
        enterButton.isHidden = true
    }
    
    override func didMoveToWindow() {
        
    }
}

extension WBNewFeatureView: UIScrollViewDelegate{
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        //1. 滚动到最后一屏，让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        enterButton.isHidden = true
        //计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        //设置分页控件
        pageControl.currentPage = page
        
        //分页控件隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
